/**
   DataLogger for EMMA
 Copyright (C) 2015  Rodrigo Garcia

 This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/
// See header for reference
#include "DataLogger.h"

char Set_DatalogMetaData (struct LogFile *logfile, unsigned char *file_name, char appendName)
{
  // TODO: Control strings size
  if(appendName)
    sprintf(logfile->FileName,"%s%s", logfile->FileName, file_name);
  else
    //    printf("[DATALOGGER] nu nom..\n"); //debug
    sprintf(logfile->FileName,"%s", file_name);

  return 0;
}

char Set_DatalogTime(struct LogFile *logfile, char *time, char appendTime)
{
  // TODO: Control strings size

  if(appendTime)
    sprintf(logfile->time, "%s%s", logfile->time, time);
  else
    sprintf(logfile->time, "%s", time);

  return 0;
}

// Log into file (See Docu/datalog_format)
void LogIntoFile(struct LogFile *logfile)
{
  char str_buff[25];
  // File header see Docu/datalog_format
  if(change_table_header)
    {
      sprintf(str_buff, "\r");
      // === First Row ===
      sprintf(str_buff, "%s        \t",str_buff); // BR
      addToNewContentBuffer(str_buff, 0); // rewrite
      //SD_writeFile(logfile->FileName, str_buff);
      // Physical Phenomenon Names
      if(temperature_ctrl)
	{
	  Copy_STR_Physical_Phenomenon(str_buff, TEMPERATURE);
	  sprintf(str_buff, "%s\t", str_buff);
	  sprintf(str_buff, "%sC \t\t"); //FIXME: uniq units?
	  
	  addToNewContentBuffer(str_buff, 1);
	  //SD_writeFile(logfile->FileName, str_buff);
	}
      if(relative_humidity_ctrl)
	{
	  Copy_STR_Physical_Phenomenon(str_buff, RELATIVE_HUMIDITY);
	  sprintf(str_buff, "%s\t", str_buff);
	  sprintf(str_buff, "%s%% \t\t", str_buff);

	  addToNewContentBuffer(str_buff, 1);
	  //SD_writeFile(logfile->FileName, str_buff);
	}

      addToNewContentBuffer("\r", 1);
      //SD_writeFile(logfile->FileName, new_content_buffer); // save to file

      // ======
      // === Second Row ===
      Copy_STR_Physical_Phenomenon(str_buff, TIME);

      sprintf(str_buff, "%s\t", str_buff);
      addToNewContentBuffer(str_buff, 1);
      //SD_writeFile(logfile->FileName, str_buff);

      // Sensors names
      // TODO: iterate trough sensors names automatically
      if(temperature_ctrl)
	{
	  if(temperature_ctrl & (1<<LM35)) // sensor LM35
	    {
	      Copy_STR_SensorsNamesTemperature1(str_buff, LM35);
	      sprintf(str_buff, "%s\t", str_buff);
	      addToNewContentBuffer(str_buff, 1);
	      //SD_writeFile(logfile->FileName, str_buff);
	    }
	  if(temperature_ctrl & (1<<DHT11)) // sensor DHT11
	    {
	      Copy_STR_SensorsNamesTemperature1(str_buff, DHT11);
	      sprintf(str_buff, "%s\t", str_buff);
	      addToNewContentBuffer(str_buff, 1);
	      //SD_writeFile(logfile->FileName, str_buff);
	    }
	  // More sensors
	  //..
	  
	  addToNewContentBuffer("\t\t", 1);
	  //SD_writeFile(logfile->FileName);
	}
      if(relative_humidity_ctrl)
	{
	  if(relative_humidity_ctrl & (1<<DHT11))
	    {
	      Copy_STR_SensorsNamesRelativeHumidity(str_buff, DHT11);
	      sprintf(str_buff, "%s\t", str_buff);
	      addToNewContentBuffer(str_buff, 1);
	      //SD_writeFile(logfile->FileName, str_buff);
	    }

	  addToNewContentBuffer("\t\t",1);
	}

      addToNewContentBuffer("\r", 1);

      SD_writeFile(logfile->FileName, new_content_buffer); // save first two rows on a File 
      change_table_header = 0;
      // ======
    }

  // Hour
  addToNewContentBuffer(logfile->time, 0); // new content
  addToNewContentBuffer("\t", 1);
  //SD_writeFile(logfile->FileName, logfile->time);
  //SD_writeFile(logfile->FileName, "\t");// separator

  float last_sensor_response;
  //=== DATA row ===
  // iterates on all sensors and see if they're enabled

  // 1: Keep the order of Names an data from sensors
  // Sensor's response
  if(temperature_ctrl) //temperature
    {
      if(temperature_ctrl & (1<<LM35))
	;
      if(temperature_ctrl & (1<<DHT11))
	{
	  last_sensor_response = dht11_get_Temperature();
	  AppendAndCheckValidDataFromSensor(last_sensor_response, logfile->FileName);
	}
	addToNewContentBuffer("\t\t", 1);
    }
  if(relative_humidity_ctrl) //relative humidity
    {
      if(relative_humidity_ctrl & (1<<DHT11))
	{
	  last_sensor_response = dht11_get_RelativeHumidity();
	  AppendAndCheckValidDataFromSensor(last_sensor_response, logfile->FileName);
	}

      addToNewContentBuffer("\t\t", 1);
    }
  // ======

  // The FAT32 library seems to add \n after \r automatically
  addToNewContentBuffer("\r", 1);
  SD_writeFile(logfile->FileName, new_content_buffer);

  // TODO: Add error return (is it necessary?)
  //  return 0;
}


// Utilities
void AppendAndCheckValidDataFromSensor(float sensor_data_read, const char *filename)
{
  unsigned char data_string[11];

  if(sensor_data_read == SENSOR_NO_ANSWER)
    sprintf(data_string, "Err"); //error
  else
    sprintf(data_string, "%4.3f", sensor_data_read);

  addToNewContentBuffer(data_string, 1);
  addToNewContentBuffer("\t", 1); // separator
  //SD_writeFile(filename, data_string);
  //SD_writeFile(filename, "\t");// separator
}



/* void NumShortToString(char *str_dest, char num) */
/* { */
/*   // FIXME:  negative numbers are not being working! */
/*     unsigned char i=0; */
/*     unsigned char c=0; */
/*     unsigned char aux1[5]; */
/*     unsigned char aux2[5]; */
/*     if(num<0) // negative */
/*       { */
/* 	aux2[0]= '-'; */
/* 	c++; */
/* 	num *= -1; */
/*       } */
/*     do */
/*       { */
/* 	aux1[i++] = num%10 + 0x30; */
/* 	num /= 10; */
/*       } while (num>0 && i<5); */
/*     aux1[i] = '\0'; */
/*     while(i--) */
/*       aux2[c++] = aux1[i]; */
/*     aux2[c] = '\0'; */

/*     sprintf(str_dest, "%s",aux2); // copy int char_num_str */
/* } */


/* void NumMedToString(char *str_dest, int num) */
/* { */
/*     unsigned char i=0; */
/*     unsigned char c=0; */
/*     unsigned char aux1[8]; */
/*     unsigned char aux2[8]; */
/*     if(num<0) // negative */
/*       { */
/* 	aux2[0]= '-'; */
/* 	c++; */
/* 	num *= -1; */
/*       } */
/*     do */
/*       { */
/* 	aux1[i++] = num%10 + 0x30; */
/* 	num /= 10; */
/*       } while (num>0 && i<5); */
/*     aux1[i] = '\0'; */
/*     while(i--) */
/*       aux2[c++] = aux1[i]; */
/*     aux2[c] = '\0'; */

/*     sprintf(str_dest, "%s",aux2); // copy int char_num_str */
/* } */
